package com.chinawlx.wlxteacher.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.chinawlx.wlxteacher.R;
import com.chinawlx.wlxteacher.network.WLXHttpRxHelper;
import com.chinawlx.wlxteacher.network.bean.WLXGetCodeBean;
import com.chinawlx.wlxteacher.network.bean.WLXUploadImagesBean;
import com.chinawlx.wlxteacher.utils.WLXFileUtil;
import com.chinawlx.wlxteacher.utils.WLXGreenDaoUtil;
import com.chinawlx.wlxteacher.utils.WLXImageUtils;
import com.chinawlx.wlxteacher.utils.WLXLogUtil;
import com.chinawlx.wlxteacher.utils.WLXTeacherConstant;
import com.chinawlx.wlxteacher.widget.WLXCustomToast;
import com.chinawlx.wlxteacher.wlx_file;
import com.chinawlx.wlxteacher.wlx_fileDao;

import java.io.File;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import rx.Subscriber;
import wlx.wm.photopicker.widget.MultiPickResultView;

/**
 * 课程内容界面
 *
 * Created by wlx on 16/8/18.
 * <p/>
 * 课程内容界面
 * 提交学习内容
 * 说明：分两步操作，第一步：调用下面的api提交文本信息，第二步调用图片上传接口
 * ----------------------
 * 请求类型：POST
 * 请求地址：http://192.168.0.107:8001/client/android/:client_type/v1/schedule/setcontent/:schedule_id
 * 请求参数:
 * content: 文字内容
 * ----------------------------
 * 上传图片附件
 * 说明： resource_code（schedule：课程表内容 ｜ homework：作业｜homework_comment：作业评价）
 * ----------------------------
 * 请求方法：POST
 * 请求地址：http://192.168.0.107:8001/client/android/:client_type/v1/upload/image
 * 请求参数：
 * resource_id：资源id
 * resource_code：资源编码
 * file: 文件数据
 */
public class WLXCourseContentActivity extends WLXBaseActivity {
    @BindView(R.id.et_content_course_content)
    EditText inputContent;
    @BindView(R.id.tv_num_course_content)
    TextView inputNum;
    @BindView(R.id.multiPickResultView)
    MultiPickResultView mMultiPickResultView;

    private int mImageIndex = 0;//正在上传图片的索引

    /**
     * 保存将要发送的图片路径
     */
    private ArrayList<String> mImagePathList = new ArrayList<>();
    private String mSchedule_id;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_course_content);
        ButterKnife.bind(this);
        init();
    }

    private void init() {
        mSchedule_id = getIntent().getStringExtra(WLXTeacherConstant.SCHEDULE_ID);
        inputContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                inputNum.setText(0 + s.length() + "/150");
            }
        });

        //初始化已选择的图片
        mMultiPickResultView.init(this, MultiPickResultView.ACTION_SELECT, mImagePathList);
    }

    @OnClick({R.id.tv_send_course_content,R.id.iv_back_course_call_roll})
    public void OnClick(View view) {
        switch (view.getId()) {
            case R.id.tv_send_course_content:
                mImagePathList.clear();
                ArrayList<String> photos = mMultiPickResultView.getPhotos();
                mImagePathList.addAll(photos);

                String content = inputContent.getText().toString();
                if (!TextUtils.isEmpty(content)) {
                    sendContent(content);
                    if (mImagePathList.size()>0){
                        //上传第一张
                        mImageIndex = 0;
                        sendImages(mImagePathList.get(mImageIndex));
                    }
                }else {
                    WLXCustomToast.show("请添加课堂内容");
                }
//                if (mImagePathList.size()>0){
//                    //上传第一张
//                    mImageIndex = 0;
//                    sendImages(mImagePathList.get(mImageIndex));
//                }
                break;
            case R.id.iv_back_course_call_roll:
                onBackPressed();
                break;
        }
    }

    private void sendContent(String content) {
        WLXHttpRxHelper.getInstance().scheduleSetcontent(mSchedule_id, content, new
                Subscriber<WLXGetCodeBean>() {

                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        WLXCustomToast.show("文本发送失败");
                    }

                    @Override
                    public void onNext(WLXGetCodeBean wlxGetCodeBean) {
                        if (wlxGetCodeBean.getCode() == 0) {
                            WLXCustomToast.show("文本发送成功");
                            finish();
                        } else {
                            WLXCustomToast.show("文本发送失败");
                        }
                    }
                });
    }


    /**
     * 上传图片文件
     */
    private void sendImages(String imagePath) {
        Map<String, RequestBody> params = new LinkedHashMap<>();
        File file;

        final double size = WLXFileUtil.getFileOrFilesSize(imagePath, WLXFileUtil
                .SIZETYPE_KB);
        WLXLogUtil.printE("压缩前图片大小:"+size);
        if (size > 500){
            //如果图片大小大于500K,就处理图片大小(系统相机拍的大图)
            file = new File(WLXImageUtils.zoomBitmap2File(imagePath));
        }else {
            file = new File(imagePath);
        }
        WLXLogUtil.printE("压缩后图片大小:"+WLXFileUtil.getFileOrFilesSize(file.getAbsolutePath(),WLXFileUtil.SIZETYPE_KB));


        RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        //file代表服务器接收到的key,file1.getName()代表文件名
        params.put("file\";filename=\"" + file.getName(), requestBody);

        params.put("resource_id", RequestBody.create(MediaType.parse("multipart/form-data"),
                mSchedule_id));
        params.put("resource_code", RequestBody.create(MediaType.parse("multipart/form-data"),
                "schedule"));

        WLXHttpRxHelper.getInstance().uploadImages(params, new Subscriber<WLXUploadImagesBean>() {

            @Override
            public void onStart() {
                super.onStart();
                WLXCustomToast.showTopToast("正在上传第" + (mImageIndex + 1) + "张图片");
            }

            @Override
            public void onCompleted() {
                //=======================上传之后图片不能删除(有可能是相册图片,不是app拍的)

                //最后一张上传成功之后,刷新界面
                if (mImageIndex == mImagePathList.size() - 1) {
                    List<wlx_file> fileList = WLXGreenDaoUtil.getFileDao().queryBuilder().where
                            (wlx_fileDao.Properties.Resource_id.eq(mSchedule_id)).list();
                    if (fileList.size() > 0) {
                        wlx_file wlxFile = fileList.get(0);
                        WLXGreenDaoUtil.getFileDao().delete(wlxFile);
                    }
                    WLXCustomToast.showTopToast("所有图片上传完成");
                    onBackPressed();
                }
            }

            @Override
            public void onError(Throwable e) {
                onCompleted();
                WLXCustomToast.showTopToast("上传图片出现错误");
            }

            @Override
            public void onNext(WLXUploadImagesBean uploadImagesBean) {
                if (uploadImagesBean.getCode() == 0) {
                    WLXCustomToast.showTopToast("第" + (mImageIndex + 1) + "上传成功");
                    //=============================前一张图片上传成功之后继续传下一张
                    if (mImageIndex < mImagePathList.size() - 1) {
                        mImageIndex++;
                        sendImages(mImagePathList.get(mImageIndex));
                    }
                } else {
                    WLXCustomToast.show(uploadImagesBean.getMsg());
                }
            }
        });

    }

    @Override
    public void onBackPressed() {
        finishSelf();
    }

    public void finishSelf(){
        finish();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        mMultiPickResultView.onActivityResult(requestCode, resultCode, data);
    }
}
